package com.fs.chatx.module.chat.api;
import com.alibaba.fastjson.JSONObject;
import com.fs.chatx.core.api.R;
import com.fs.chatx.core.exception.ApiException;
import com.fs.chatx.core.util.PromtUtil;
import com.fs.chatx.module.chat.config.PromptConfig;
import com.fs.chatx.module.chat.service.DeepseekService;
import com.fs.chatx.module.chat.service.OcrService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api")
public class OcrController
{

    @Autowired
    private OcrService ocrService;

    @Autowired
    private PromptConfig promptConfig;

    @Autowired
    private DeepseekService deepseekService;

    @PostMapping(value = "/ocrStruct")
    public R ocrStruct(String orginReport)
    {
        if(StringUtils.isEmpty(orginReport))
        {
            return R.success();
        }
        try
        {
            orginReport=orginReport.replace("\\n"," ");
            StringBuffer structPrompt =new StringBuffer("医学报原始报告:\n ");
            structPrompt.append(orginReport);
            File file = ResourceUtils.getFile("classpath:prompts/medical_report_prompt.yaml");
            String extractionPrompt = new String(Files.readAllBytes(file.toPath()));
            extractionPrompt= PromtUtil.renderPrompt(
                    extractionPrompt,
                    Map.of("text", orginReport)
            );
          //  String extractionPrompt = new String(Files.readAllBytes(Paths.get("prompts/medical_report_prompt.yaml")));
            String result=deepseekService.structReport(extractionPrompt,"");
            log.info(result);
            return R.success( JSONObject.parse(result.replace("```json", "").replace("```", "")) ) ;
        }catch (Exception e){
            e.printStackTrace();
            throw new ApiException("ocrStruct structure error");
        }
    }




}
